<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
// 注意，我们要继承的是 jwt 的 BaseMiddleware
class RefreshToken extends BaseMiddleware
{

    /**
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|mixed
     * @throws JWTException
     */
    public function handle($request, Closure $next)
    {
        //BaseMiddleware内方法
        try{
            if ($userInfo = $this->auth->parseToken()->authenticate()) {
                $time = Auth::guard('rider')->payload()['exp'];
                //刷新Token
                if(($time - time()) < 10*60 && ($time - time()) > 0){
                    $token = Auth::guard('rider')->refresh();
                    if($token){
                        $request->headers->set('Authorization', 'Bearer '.$token);
                    }else{
                        return response(['code'=>401,'msg'=>'The token has been blacklisted'],401);
                    }

                    // 在响应头中返回新的 token
                    $respone = $next($request);
                    if(isset($token) && $token){
                        $respone->headers->set('Authorization', 'Bearer '.$token);
                    }
                    return $respone;
                }
                return $next($request);
            }
            throw new UnauthorizedHttpException('jwt-auth', '未登录');
        }catch (TokenExpiredException $exception){
            //是否可以刷新,刷新后加入到响应头
            throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage());
        }
    }
}
